package com.hcy.mqbusiness.mqcenterfororder;

import com.hcy.mqbusiness.MqProducer;
import com.hcy.rabbitbasicmodel.enums.Code;
import com.hcy.rabbitbasicmodel.model.ResponseData;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @Author huchenying
 * @Description
 * @Date 2022/3/15 14:40
 */
@Service
public class RocketMqDelayProducer implements MqProducer {

    private final DefaultMQProducer syncDelayProducer = new DefaultMQProducer("delayProducer");

    static Logger logger = LoggerFactory.getLogger(RocketMqDelayProducer.class);

    @Value("${MQ.namesrvAddr}")
    private String namesrvAddr;

    @PostConstruct
    private void init(){
        syncDelayProducer.setNamesrvAddr(namesrvAddr);
        // 设置配置，可以从配置中拿，暂时使用固定数据
        syncDelayProducer.setRetryTimesWhenSendFailed(3);
        syncDelayProducer.setSendMsgTimeout(3000);
        //设置新创建的Topic的Queue数量为4
        syncDelayProducer.setDefaultTopicQueueNums(4);
        //设置vip通道，防止消费超时
        syncDelayProducer.setSendMessageWithVIPChannel(false);
        try {
            syncDelayProducer.start();
        } catch (MQClientException e) {
            logger.error("syncProducer 启动失败！");
            e.printStackTrace();
        }
    }

    /**
     * @Author huchenying
     * @Description 发送一个同步消息
     * @Date 2022/3/15 14:45
     **/
    public ResponseData<SendResult> sendSyncMessage(Message message){
        ResponseData<SendResult> responseData = new ResponseData<>();
        try {
            SendResult send = syncDelayProducer.send(message);
            responseData.setData(send);
            responseData.setCode(Code.Success);
            return responseData;
        } catch (MQClientException | RemotingException | MQBrokerException | InterruptedException e) {
            e.printStackTrace();
            responseData.setMsg("服务器异常，延迟消息发送失败！");
            responseData.setCode(Code.Exception);
            return responseData;
        }
    }
    @PreDestroy
    private void shudown(){
        syncDelayProducer.shutdown();
    }
}
